//
// Created by hunan on 2025/10/1.
//

#include "hls_fragment.h"
#include "hls_m3u8_message.h"

HlsFragment::HlsFragment(HlsM3U8Message * message)
{
    m_message = message;
    FragmentHlsMessage();
}

std::string HlsFragment::GetOneFragment(int & index)
{
    std::string value;
    index = -1;
    for (auto & item : m_fragments)
    {
        if (item.second.m_status == EmFragmentStatus::EmInit || item.second.m_status == EmFragmentStatus::EmFailed)
        {
            const auto & uri_vec = m_message->UriIndex();
            index = item.second.m_index;
            value = uri_vec[index].m_index_uri;
            item.second.m_status = EmUsed;
            break;
        }
    }
    return value;
}

void HlsFragment::UpdateFragmentFailed(int index)
{
    auto iter = m_fragments.find(index);
    if (iter != m_fragments.end())
    {
        iter->second.m_status = EmFragmentStatus::EmFailed;
    }
}

void HlsFragment::UpdateFragmentSuccess(int index)
{
    auto iter = m_fragments.find(index);
    if (iter != m_fragments.end())
    {
        iter->second.m_status = EmFragmentStatus::EmDone;
    }
}

int HlsFragment::AllFragmentSuccess() const
{
    for (auto & item : m_fragments)
    {
        if (item.second.m_status != EmFragmentStatus::EmDone)
        {
            return false;
        }
    }
    return true;
}


void HlsFragment::FragmentHlsMessage()
{
    if (m_message)
    {
        auto & uri_vec = m_message->UriIndex();
        int index = 0;
        for (auto uri : uri_vec)
        {
            auto & item = m_fragments[index];
            item.m_index  = index;
            item.m_status = EmFragmentStatus::EmInit;
            index++;
        }
    }
}




